#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"

trigger-scheduler-docker-local-scheduler-tags-create() {
  declare desc="scheduler-docker-local scheduler-tags-create plugin trigger"
  declare trigger="scheduler-tags-create"
  declare DOKKU_SCHEDULER="$1" APP="$2" SOURCE_IMAGE="$3" TARGET_IMAGE="$4"

  if [[ "$DOKKU_SCHEDULER" != "docker-local" ]]; then
    return
  fi

  local TAG_OPTS=""
  [[ $(is_tag_force_available) ]] && TAG_OPTS="-f"
  # shellcheck disable=SC2086
  "$DOCKER_BIN" image tag $TAG_OPTS "$SOURCE_IMAGE" "$TARGET_IMAGE"
}

is_tag_force_available() {
  CLIENT_VERSION_STRING="$(get_docker_version)"
  MAJOR_VERSION=$(echo "$CLIENT_VERSION_STRING" | awk '{split($0,a,"."); print a[1]}')
  MINOR_VERSION=$(echo "$CLIENT_VERSION_STRING" | awk '{split($0,a,"."); print a[2]}')
  PATCH_VERSION=$(echo "$CLIENT_VERSION_STRING" | awk '{split($0,a,"."); print a[3]}')

  # docker tag -f was dropped in 1.12.0
  if [[ "$MAJOR_VERSION" -gt 1 ]]; then
    return 1
  elif [[ "$MAJOR_VERSION" -eq 1 ]] && [[ "$MINOR_VERSION" -ge 12 ]]; then
    return 1
  else
    return 0
  fi
}

trigger-scheduler-docker-local-scheduler-tags-create "$@"
